<template>
    <a-modal
        v-model:open="open"
        :title="props.user_lib_id != undefined ? '添加人脸' : '新建人脸集'"
        @ok="handleOk"
        :width="680"
        :destroyOnClose="true"
        :model="facialSet"
        :maskClosable="false"
        v-bind="$attrs"
    >
        <a-form
            layout="vertical"
            :rules="rules"
            autocomplete="off"
            ref="formRef"
            :model="facialSet"
        >
            <a-form-item label="人脸集名称" name="user_name">
                <a-input
                    show-count
                    :maxlength="20"
                    v-model:value="facialSet.user_name"
                ></a-input>
            </a-form-item>
            <a-form-item label="职务" name="duties">
                <a-input show-count v-model:value="facialSet.duties"></a-input>
            </a-form-item>
            <a-form-item label="上传图片" name="urls">
                <UploadImg
                    ref="uploadImgRef"
                    v-bind="$attrs"
                    :disabled="submitLoading"
                    :init-img-urls="facialSet.user_image"
                />
            </a-form-item>
        </a-form>
        <template #footer>
            <div class="btns" v-if="!submitLoading">
                <a-button @click="hdlCancel">取消</a-button>
                <a-button type="primary" @click="handleOk">确定</a-button>
            </div>
        </template>
    </a-modal>
</template>

<script setup lang="ts">
    import { facialSetService } from "@/service/faceLibrary.service";
    import { FacialSet } from "@/type/faceLibrary";
    import getRuleByName from "@/utils/formRules";
    import { h, ref, watch } from "vue";
    import UploadImg from "../UploadImg/UploadImg.vue";
    import { message } from "ant-design-vue";
    import { notification } from "ant-design-vue";
    import encodeURI2 from "@/utils/encodeURI";
    const facialSet = ref(new FacialSet());
    const props = withDefaults(
        defineProps<{
            // face_lib_id?: string;
            user_lib_id: string;
            user_name: string;
            onUploadSuccess?: () => void;
        }>(),
        {
            // face_lib_id: "",
            user_lib_id: "",
            user_name: "",
        },
    );

    // watch(
    //     () => props,
    //     (newValue) => {
    //         facialSet.value.face_lib_id = newValue.face_lib_id;
    //         facialSet.value.user_lib_id = newValue.user_lib_id;
    //     },
    //     {
    //         immediate: true,
    //     },
    // );
    watch(
        () => props.user_name,
        (newValue) => {
            facialSet.value.user_name = newValue;
        },
        {
            immediate: true,
        },
    );

    const open = ref(false);
    const submitLoading = ref(false);
    const uploadImgRef = ref();
    const formRef = ref();
    const errorMsg = ref([]);
    const handleOk = () => {
        formRef.value
            .validate()
            .then(() => {
                submitLoading.value = true;
                uploadImgRef.value.hdlUpload(async (urls: string[]) => {
                    facialSet.value.user_image = urls;
                    let msg = "";
                    try {
                        let res = await facialSetService.add(facialSet.value);
                        // refresh();
                    } catch (err: any) {
                        try {
                            msg = err.data.msg;
                            errorMsg.value = err.data.msg
                                ? JSON.parse(err.data.msg)
                                : [err.data.msg];
                            let errorObj: any = {};
                            errorMsg.value.forEach((item: string) => {
                                let [k, v] = item.split(":");
                                errorObj[k] = v;
                            });
                            let imgNames = Object.keys(errorObj);

                            notification.error({
                                class: "face-upload-error",
                                duration: 10,
                                message: "上传图片错误",
                                description: h(
                                    "div",
                                    imgNames.map((name: string) => {
                                        return h(
                                            "div",
                                            { class: "error-item" },
                                            [
                                                h("img", {
                                                    class: "icon",
                                                    src: encodeURI2(
                                                        urls.find((url) =>
                                                            url.includes(name),
                                                        )!,
                                                    ),
                                                }),
                                                h("div", { class: "msg-box" }, [
                                                    h(
                                                        "div",
                                                        { class: "error-msg" },
                                                        errorObj[name],
                                                    ),
                                                    h(
                                                        "div",
                                                        { class: "name" },
                                                        name,
                                                    ),
                                                ]),
                                            ],
                                        );
                                    }),
                                ),
                            });
                            uploadImgRef.value.clearProgress();
                        } catch (err) {
                            message.error(msg);
                        }
                    } finally {
                        open.value = false;
                        props.onUploadSuccess && props.onUploadSuccess();
                        submitLoading.value = false;
                    }
                });
            })
            .catch((err: any) => {
                console.log(err);
            });
    };

    const hdlCancel = () => {
        open.value = false;
        if (!props.user_lib_id) {
            facialSet.value.user_name = "";
            facialSet.value.user_image = [];
        }
    };

    const hdlClose = () => {
        errorMsg.value = [];
    };

    const rules = {
        user_name: [getRuleByName("required", "请输入人脸集名称")],
        urls: [
            {
                required: true,
                validator: (rule: any, value: string[]) => {
                    if (uploadImgRef.value.selectedImgsViews?.length <= 0) {
                        return Promise.reject("请上传图片");
                    }
                    return Promise.resolve();
                },
            },
        ],
    };

    const getFaceDetail = async (id: string) => {
        let res = await facialSetService.getDetail(id);
        let data = res.data.result.data || {};
        facialSet.value = data;
    };
    const changeOpen = (id?: string) => {
        if (!open.value) {
            if (id != undefined) {
                getFaceDetail(id);
            } else {
                facialSet.value = new FacialSet();
            }
            // if (!props.user_lib_id) {
            //     facialSet.value.user_name = "";
            //     facialSet.value.user_image = [];
            // }
        }
        open.value = !open.value;
    };
    const clearData = () => {
        facialSet.value = new FacialSet();
    };
    defineExpose({
        changeOpen,
        clearData,
    });
</script>

<style lang="scss" scoped src="./ModalUploadImg.scss"></style>
<style lang="scss" src="./ModalUploadImg.global.scss"></style>
